package cn.lexi.vip.service.sms.impl;

import cn.lexi.vip.model.sms.SmsConfig;
import cn.lexi.vip.model.sms.SmsResult;
import cn.lexi.vip.service.sms.ISmsSender;
import cn.lexi.vip.service.sms.IsmsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * Created by gaoxiang on 16/11/13.
 * 发送短信的业务类
 *
 */
@Service
public class SmsServiceImpl implements IsmsService{

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class);


    @Value("${sms.is.debug}")
    private boolean isDebug;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private GuoDuSms guoDuSms;

    private static final ISmsSender[] SMS_SENDERS = new ISmsSender[1];

    //这里-接入多个供应商时,进行切换,保证短信的到达率
    @PostConstruct
    private void init() {

        SMS_SENDERS[0] = guoDuSms;
        if (isDebug) {
            for (SmsConfig.SMS sms : SmsConfig.SMS.values()) {
                sms.setEnabled(false);
            }
            redisTemplate.opsForValue().set(SmsConfig.SMS_INDEX_KEY, "-1");
            return;
        }

        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(SmsConfig.SMS_INDEX_KEY))) {
            redisTemplate.opsForValue().set(SmsConfig.SMS_INDEX_KEY, "0");
        }
    }

    @Override
    public SmsResult send(String phone, String content) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(content)) {
            return SmsResult.error("参数错误");
        }

        /********** Debug模式 ***********/
        int smsIndex = Integer.parseInt(redisTemplate.opsForValue().get(SmsConfig.SMS_INDEX_KEY));
        if (isDebug && smsIndex < 0) {
            return SmsResult.success();
        }

        SmsResult result = SmsResult.error("发送失败");

        /********** 如果发送失败，选择其他短信平台重新发送 ***********/
        for (int i = 0; i < SMS_SENDERS.length; i++) {
            if (smsIndex >= SMS_SENDERS.length) {
                smsIndex = 0;
            }

            try {
                if (!SmsConfig.SMS.values()[smsIndex].isEnabled()) {
                    LOGGER.info("短信平台已关闭, smsIndex:{}", smsIndex);
                    smsIndex++;
                    continue;
                }
                result = SMS_SENDERS[smsIndex].send(phone, content);
            } catch (Exception e) {
                LOGGER.error("短信发送出现异常", e);
                result.setMsg("系统异常");
            }

            if (result.isRet()) {
                LOGGER.info("短信发送成功, smsIndex:{}, phone:{}, content:{}", smsIndex, phone, content);
                break;
            } else {
                LOGGER.warn("短信发送失败, smsIndex:{}, phone:{}, content:{}, reason:{}", smsIndex, phone, content, result.getMsg());
                smsIndex++;
            }
        }

        redisTemplate.opsForValue().set(SmsConfig.SMS_INDEX_KEY, smsIndex + "");

        return result;
    }
}
